package service

import (
	"fmt"
	"log"
	"strconv"
	"testhttp/dao"
	"testhttp/model"
	"time"

	"github.com/kataras/iris/v12"
)

func ListOrders(data model.HttpParamsOrder) iris.Map {

	queryparam := " is_deleted = 0 "
	if data.OrderNum != "" {
		queryparam = queryparam + "and order_num like '%" + data.OrderNum + "%'"
		log.Print("Debug queryparam1:", queryparam)
	}
	if data.Dealer != "" { //表格存储的是dealer id 。
		queryparam = queryparam + "and dealer like '%" + data.Dealer + "%'"
		log.Print("Debug queryparam2:", queryparam)
	}
	res_order, count := dao.ListOrder(fmt.Sprint(queryparam), data.Pagesize, data.Page)

	// log.Print("Debug res_order:", res_order)
	respones := iris.Map{
		"code":  0,
		"msg":   "OK",
		"count": count,
		"data":  RepOrders(res_order),
	}
	return respones

}

func RepOrders(data []model.Orders) []model.ListOrders {
	res := make([]model.ListOrders, len(data))
	for x := 0; x < len(data); x++ {
		res[x].Id = data[x].Id
		res[x].OrderNum = data[x].OrderNum + "\t"
		res[x].Goods = data[x].Goods

		if data[x].GoodsSku == "" {
			res[x].GoodsSku = "默认"
		} else {
			res[x].GoodsSku = data[x].GoodsSku
		}

		res[x].SumGoods = data[x].SumGoods

		res[x].MemName = data[x].MemName
		res[x].MemPhone = data[x].MemPhone
		res[x].XiangxiDz = data[x].XiangxiDz

		if data[x].Offers == "" {
			res[x].Offers = "0"
		} else {
			res[x].Offers = data[x].Offers
		}

		if data[x].Postage == "" {
			res[x].Postage = "0"
		} else {
			res[x].Postage = data[x].Postage
		}

		res[x].Remark = data[x].Remark
		res[x].Remark1 = data[x].Remark1

		d, errd := GetDealerbyId(data[x].DealerId)
		if errd != nil || len(d) == 0 {
			log.Print("Service GetDealerbyId error:", errd)
			res[x].Dealer = ""
			res[x].Shop = ""
			res[x].ShipConditions = ""
			res[x].OrderType = ""
		} else {
			res[x].Dealer = d[0].Dealer
			res[x].Shop = d[0].Shop
			res[x].ShipConditions = d[0].ShipConditions
			res[x].OrderType = d[0].OrderType
		}

		g, errg := GetGoodsby(data[x].Goods, data[x].GoodsSku)
		if errg != nil || len(g) == 0 {
			log.Print("Service GetGoodsby error:", errg)
			res[x].GoodsCode = ""
			res[x].WareHouse = ""
			res[x].SupplyPrice = ""
			res[x].SumGoodsPrice = ""
		} else {
			res[x].GoodsCode = g[0].GoodsCode
			res[x].WareHouse = g[0].WareHouse
			res[x].SupplyPrice = g[0].SupplyPrice
			a, _ := strconv.ParseFloat(g[0].SupplyPrice, 64)
			b, _ := strconv.ParseFloat(data[x].SumGoods, 64)
			c := a * b
			res[x].SumGoodsPrice = strconv.FormatFloat(c, 'f', 2, 64) //float64，f 不做科学计数，保留2为小数
		}
		res[x].TotalOrder = data[x].TotalOrder
	}
	for k, v := range res {
		var total float64
		for x := 0; x < len(res); x++ {

			if v.OrderNum == res[x].OrderNum {

				// log.Println("Debug sumif:", x, "//", res[x].OrderNum, "//", res[x].SumGoodsPrice)
				a, _ := strconv.ParseFloat(res[x].SumGoodsPrice, 64)

				total += a
			}
		}
		res[k].TotalOrder = strconv.FormatFloat(total, 'f', 2, 64) //float64，f 不做科学计数，保留2位小数
	}
	return res
}

func AddOrders(data []model.Orders) iris.Map {
	log.Print("Debug input data:", data)
	var querydata []model.Orders
	now := time.Now()
	for _, v := range data {

		//验证必填数据
		switch {
		case v.OrderNum == "":
			log.Print("Error: ", v, " OrderNum is null!")
		// case v.Goods == "":
		// 	log.Print("Error: ", v, " Goods is null!")
		case v.DealerId == "":
			log.Print("Error: ", v, " DealerId is null!")
		case v.SumGoods == "":
			log.Print("Error: ", v, " SumGoods is null!")
		case v.MemName == "":
			log.Print("Error: ", v, " MemName is null!")
		case v.MemPhone == "":
			log.Print("Error: ", v, " MemPhone is null!")
		case v.XiangxiDz == "":
			log.Print("Error: ", v, " XiangxiDz is null!")
		default:
			//通过dealer_id获取dealer
			// if v.DealerId != "" && v.DealerId != "default" { //添加操作，请求数据需通过下面完善dealer。导入操作，填充dealer略过。
			// 	v.Dealer = dao.GetDealer(v.DealerId)
			// }

			// v.Goods = dao.ViewGoods(v.GoodsId)[0].Goods   //结构体缺少请求体部分字段，程序结构添加分层，衔接controller和dao的数据结构差异。

			g, errg := GetGoodsby(v.Goods, v.GoodsSku) //获取货品信息及供货价，计算货品总价
			if errg != nil || len(g) == 0 {
				log.Print("Service GetGoodsby error:", errg)
				v.GoodsCode = ""
				v.WareHouse = ""
				v.SupplyPrice = "0"
				v.SumGoodsPrice = "0"
				v.TotalOrder = "0"
			} else {
				v.GoodsCode = g[0].GoodsCode
				v.WareHouse = g[0].WareHouse
				v.SupplyPrice = g[0].SupplyPrice
				a, _ := strconv.ParseFloat(g[0].SupplyPrice, 64)
				b, _ := strconv.ParseFloat(v.SumGoods, 64)
				c := a * b
				v.SumGoodsPrice = strconv.FormatFloat(c, 'f', 2, 64) //float64，f 不做科学计数，保留2为小数

			}
			// 初始化通用字段
			v.CreateTime = now
			v.UpdateTime = now
			v.IsDeleted = 0

			querydata = append(querydata, v)
		}
	}

	success := dao.InsertOrders(SumTotal(querydata))

	res := iris.Map{
		"code":    0,
		"msg":     "OK",
		"submit":  len(data),      //提交数据条数
		"new":     len(querydata), //新数据条数
		"success": success,        //成功插入数据
	}
	return res
}

func SumTotal(data []model.Orders) []model.Orders { //计算订单应收合计

	for k, v := range data {
		var total float64
		for x := 0; x < len(data); x++ {

			if v.OrderNum == data[x].OrderNum {

				log.Println("Debug sumif:", x, "//", data[x].OrderNum, "//", data[x].SumGoodsPrice)
				a, _ := strconv.ParseFloat(data[x].SumGoodsPrice, 64)

				total += a
			}
		}
		data[k].TotalOrder = strconv.FormatFloat(total, 'f', 2, 64) //float64，f 不做科学计数，保留2位小数
	}
	return data
}
